package cn.itsource.ymcc.interceptor;

import cn.itsource.jwt.*;
import cn.itsource.result.JSONResult;
import cn.itsource.ymcc.config.ExcludeProperties;
import cn.itsource.ymcc.jwt.UserInfo;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.security.PublicKey;
import java.util.List;

@Slf4j
@Component
public class LoginAndPermissionInterceptor implements GlobalFilter, Ordered {

    //网关过滤器放行地址
    @Autowired
    private ExcludeProperties excludeProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        try {
            //1.判断本次请求的资源路径是否在yml配置的放行列表中 如果在就放行
            log.info("yml配置的放行列表：{}", excludeProperties);
            //获取本次请求地址
            RequestPath path = request.getPath();
            //放行地址
            Boolean excluded = excludeProperties.isExcluded(path.value());
            if(excluded){
                //登录接口放行
                return chain.filter(exchange);
            }

            //获取请求头
            List<String> tokens = exchange.getRequest().getHeaders().get(UserContext.JWT_TOKEN_HEADER_NAME);
            if(tokens != null && tokens.size() > 0){
                String jwtToken = tokens.get(0);
                log.info("获取到请求头中的token：{}", jwtToken);
//                if(StringUtils.hasText(jwtToken)){
//                    //2.工具类解析JWT字符串
//                    //publicKey解密
//                    PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
//                    Payload<UserInfo> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, UserInfo.class);
//                    if(payload != null && payload.getUserInfo() != null){
//                        //已登录  放行
//                        return chain.filter(exchange);
//                    }
//                }
                //调用工具类直接获取当前登录用户的信息
                Login login = UserContext.getUser(jwtToken);
                if(login != null ){
                    //已登录  放行
                    return chain.filter(exchange);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        // 5.否，拦截
//        // 5.1.设置状态码 401表示未登录
//        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//        // 5.2.拦截请求
//        return exchange.getResponse().setComplete();
        //未登录：被拦截；返回noLogin
        response.getHeaders().set("content-type","application/json;charset=UTF-8");
        JSONResult jsonResult = JSONResult.error("noLogin");
        byte[] bytes = JSON.toJSONBytes(jsonResult);  //阿里巴巴的json
        DataBuffer wrapper = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrapper));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}